package com.example.demo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置类
 * 
 * @author zhang
 * @date 2024
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig implements AsyncConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolConfig.class);

    /**
     * 核心线程数
     */
    @Value("${spring.task.execution.pool.core-size:10}")
    private int corePoolSize;

    /**
     * 最大线程数
     */
    @Value("${spring.task.execution.pool.max-size:20}")
    private int maxPoolSize;

    /**
     * 队列容量
     */
    @Value("${spring.task.execution.pool.queue-capacity:200}")
    private int queueCapacity;

    /**
     * 线程名前缀
     */
    @Value("${spring.task.execution.thread-name-prefix:async-task-}")
    private String threadNamePrefix;

    /**
     * 空闲线程存活时间（秒）
     */
    @Value("${spring.task.execution.pool.keep-alive:60}")
    private int keepAliveSeconds;

    /**
     * 配置异步任务线程池
     * 
     * @return Executor
     */
    @Bean(name = "asyncTaskExecutor")
    public Executor asyncTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        
        // 核心线程数
        executor.setCorePoolSize(corePoolSize);
        
        // 最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        
        // 队列容量
        executor.setQueueCapacity(queueCapacity);
        
        // 线程名前缀
        executor.setThreadNamePrefix(threadNamePrefix);
        
        // 空闲线程存活时间
        executor.setKeepAliveSeconds(keepAliveSeconds);
        
        // 拒绝策略：由调用线程执行任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        
        // 等待时间
        executor.setAwaitTerminationSeconds(60);
        
        // 初始化
        executor.initialize();
        
        logger.info("异步任务线程池配置完成 - 核心线程数: {}, 最大线程数: {}, 队列容量: {}", 
                corePoolSize, maxPoolSize, queueCapacity);
        
        return executor;
    }

    /**
     * 配置 Spring 默认的异步任务执行器
     * 
     * @return Executor
     */
    @Override
    public Executor getAsyncExecutor() {
        return asyncTaskExecutor();
    }
}

